import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { changeDrawersVisible, changeToolsTab } from "../../../store/actions/groupDrawer";
import { Avatar } from "../../../components/avatar/avatar";
import { AvatarWithProfile } from "../../../components/avatarWithProfile";
import { GroupToolsDrawer } from "./GroupToolsDeawer";
import Toast from "../../../components/toast/Toast";
import { sleep } from "../../../utils/tools";
import { logoutParam } from "im_electron_sdk/dist/interfaces";
import timRenderInstance from "../../../utils/timRenderInstance";
import { updateHistoryMessageToStore } from "../../../utils/LocalStoreInstance";
import { userLogout } from "../../../store/actions/login";
import { setIsLogInAction } from "../../../store/actions/login";
import { clearConversation, updateCurrentSelectedConversation } from "../../../store/actions/conversation";
import { clearHistory } from "../../../store/actions/message";
import { useHistory } from "react-router-dom";
import { updateUserInfo } from "../../../store/actions/user";
import { NoticeShow } from "./NoticeShow";
import { EditIcon } from "../groupSetting/EditIcon";
import { Input, message } from "tea-component";
import { ConfirmDialog, ConfirmDialogRecordsType } from "../groupSetting/ConfirmDialog";
import { useDialogRef } from "../../../utils/react-use/useDialog";
import { _handleKickedout } from "../../../utils/im-sdk";
type Info = {
    faceUrl: string;
    nickName: string;
};
export const ConversationContentHeader = (props: {currentSelectedConversation }): JSX.Element => {
    const { currentSelectedConversation } = props;
    const { conv_type, conv_id, conv_profile,conv_show_name} = currentSelectedConversation;
    const { userId:UID} = useSelector((state: State.RootState) => state.userInfo);
    const [notification,setnotification] = useState("");
    const [groupid,setGroupid] = useState("");
    const [unvisualnum,setunvisualnum] = useState(0);
    const { user_profile_identifier, user_profile_nick_name,group_detial_real_member_num,group_detial_info_member_num, user_profile_face_url, user_profile_gender, user_profile_self_signature, user_profile_role, user_profile_add_permission } = conv_profile
    const profile = {
        userId: user_profile_identifier,
        nickName: user_profile_nick_name,
        faceUrl: user_profile_face_url,
        gender: user_profile_gender,
        signature: user_profile_self_signature,
        role: user_profile_role,
        addPermission: user_profile_add_permission
    }
    const [userstainf,setUserstainf] = useState("");
    const [userdetail,setuserdetail] = useState("");
    const { toolsTab, toolsDrawerVisible } = useSelector(
        (state: State.RootState) => state.groupDrawer
    );
    const dispatch = useDispatch();

    const handleClose = () => dispatch(changeDrawersVisible(false));
    const handleClick = (id: string) => dispatch(changeToolsTab(id));
    const handleShow = () => dispatch(changeDrawersVisible(true));
    const getDisplayConvInfo = () => {
        const info: Info = {
            faceUrl: "",
            nickName: "",
        };

        if (conv_type === 1) {
            info.faceUrl = currentSelectedConversation?.conv_profile?.user_profile_face_url;
            info.nickName = conv_show_name||currentSelectedConversation.conv_profile.user_profile_nick_name;
        }

        if (conv_type === 2) {
            info.faceUrl = currentSelectedConversation?.conv_profile?.group_detial_info_face_url;
            info.nickName = currentSelectedConversation?.conv_profile?.group_detial_info_group_name;
        }
        return info;
    };
    const { faceUrl, nickName } = getDisplayConvInfo();
    const logOutHandler = async () => {
        _handleKickedout();
    };
    const [showName,setShowName] = useState(nickName);
    const [isEdit, setIsEdit] = useState(false);
    useEffect(()=>{
        setShowName(nickName)
        const request = require('request')
        if(conv_type==1&& Toast.serConfig?.is_user_status=="1"){
            request.get(Toast.defaultser+'/api/app/member/userInfoByImUserId?imUserId='+conv_id,{
                headers: {
                    Authorization: Toast.token },           
            }, async (error, res) => {
                if (error) {
                    console.error(error)
                    return
                }
                let body = JSON.parse(res.body);
                if(body.code==200)
                    setuserdetail("(账号:"+body.data?.username+")-"+(body.data?.loginIp||"")+(body.data?.province||"") +body.data?.mobileType||"pc");
                else if(body.code==401){
                    await sleep(1000);
                    message.error({ style:{top:"50%"}, content: `token过期：${Toast.token},请退出后再登陆` });
                    logOutHandler();
                }
            });
            request.post(Toast.defaultser+'/api/app/member/getOnlineStateByBatch',{
                headers: {
                    Authorization: Toast.token,},           
                json: {
                    imUserIds:[conv_id]
                    }
            },async (error, res) => {
                if (error) {
                    return
                }
                const data = res.body.data?.[0];
                if(res.body.code==401){
                    await sleep(1000);
                    message.error({ style:{top:"50%"}, content: `token过期：${Toast.token},请退出后再登陆` });
                    logOutHandler();
                    return;
                }else if(res.body.code==200&& data?.remark){
                    setUserstainf(data.remark);
                }
            });
        }else{
            request.post(Toast.defaultser+'/api/app/group/groupUserNum',{
                headers: {
                    Authorization: Toast.token,},           
                json: {
                    groupId:conv_id
                    }
            },(error, res) => {
                if (error) {
                    return
                }
                const data = res.body.data;
                console.log(data);
                setuserdetail("");
                setunvisualnum(0);
                if(data?.userNum && data?.groupId){
                    setUserstainf("(人数:"+ data?.userNum+") 群号:"+data?.groupId);
                    setnotification(data.notification||"");
                    setGroupid(data?.groupId);
                    const num = data.userNum -data.actualNum
                    setunvisualnum(num);
                    dispatch(updateUserInfo({userId: UID,custominf:{userNum:num,notification:data.notification||""}}))
                }
            });
            
        }
    },[conv_id,conv_show_name]);
    useEffect(()=>{
        if(group_detial_real_member_num>0){
            setUserstainf("(人数:"+(group_detial_real_member_num+ unvisualnum)+") 群号:"+ groupid);
        }
    },[group_detial_real_member_num])
    const handleModify = async () => {
        let param  = {
          params: {
              friendship_modify_friend_profile_param_identifier: user_profile_identifier, 
              friendship_modify_friend_profile_param_item: {
                friend_profile_item_remark: showName,    //选填
            }    //选填
          },
        }
      const {code} = await timRenderInstance.TIMFriendshipModifyFriendProfile(param);
      if(code==0){
        currentSelectedConversation.conv_show_name = showName;
        dispatch(updateCurrentSelectedConversation(currentSelectedConversation));
      }
    };  
    const dialogRef = useDialogRef<ConfirmDialogRecordsType>();
    function handleInput() {
        if(showName!= nickName){
            dialogRef.current.open({
                description: `是否将备注修改为`,
                modifyContent: showName,
                onConfirm: handleModify,
              });
        }else{
            setIsEdit(false)
        }
    }
    const {
        group_detial_info_group_type: groupType,
        group_detial_info_add_option: addOption,
    } = conv_profile || {};
    // 可拉人进群条件为 当前选中聊天类型为群且群类型不为直播群且当前群没有设置禁止加入
    //const canInviteMember = conv_type === 2 && [0, 1, 2].includes(groupType);
    const popupContainer = document.getElementById("messageInfo");

    return (
        <>
            <header className="message-info-view__header">
            <div  className="message-info-view__header--avatar"   onClick={() => {
                    if (conv_type === 2) {
                        if (toolsDrawerVisible) {
                            handleClose();
                            handleClick("");
                        } else {
                            handleShow();
                            handleClick("announcement");
                        }
                    }
                }}>
                {
                    conv_type === 1 ?  <AvatarWithProfile profile={profile} /> :
                        <Avatar  url={faceUrl}  size="small"  nickName={nickName}  userID={conv_id}  groupID={conv_id} />
                }
                {isEdit? (
                    <Input style={{width:"150px",marginLeft:"8px"}}  className="group-introduction--input"  size="full"  placeholder="输入备注后按回车"  value={showName}
                        onChange={(value) => {
                            setShowName(value);
                        }}
                        onBlur={handleInput}
                        onKeyDown={(e) => {
                            if (e.key === "Enter") {
                                handleInput();
                            }
                        }}
                    />): <span className="message-info-view__header--name">{showName}</span>
                }
                {conv_type === 1&&<EditIcon  onClick={() =>{setIsEdit(!isEdit)}} />}
                <span>{userstainf}</span><span style={{color:"#92d17b",fontSize:"11px",marginLeft:"10px"}}>{userdetail}</span>
            </div>
            {/* {canInviteMember ? <AddUserPopover groupId={conv_id} /> : <></>} */}
            <GroupToolsDrawer visible={toolsDrawerVisible} toolId={toolsTab}  conversationInfo={currentSelectedConversation} 
                popupContainer={popupContainer} onClose={() => {
                    handleClick("");
                    handleClose();
                }}
            />
        </header>
        {conv_type === 2 && notification?.length>0 &&(<NoticeShow text={notification}></NoticeShow>)}
        <ConfirmDialog  dialogRef={dialogRef}  onSuccess={() => {
            setIsEdit(false);}}
        />
        </>
    )
} 